package com.guoxin.mashibing.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author guoxin
 * @date 2019/7/11
 */
public class TicketSeller3 {

    private static Queue<String> tickets = new ConcurrentLinkedQueue<>();
    private static final List<Thread> THREAD_LIST = new ArrayList<>();
    static {
        IntStream.rangeClosed(1, 1000).forEach(num -> tickets.add("票编号：" + num));
    }


    public static void main(String[] args) throws InterruptedException {
        long begin = System.currentTimeMillis();
        IntStream.rangeClosed(1,10).forEach(i->{
            Thread ts = new Thread("窗口" + i){
                @Override
                public void run() {
                    while (true) {
                        String s = tickets.poll();
                        if (s==null) {
                            break;
                        }
                        System.out.println(Thread.currentThread().getName() + "，销售了--" + s);
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            THREAD_LIST.add(ts);
            ts.start();
        });

        Thread.sleep(100);

        THREAD_LIST.forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("main end ....");
        long end = System.currentTimeMillis();
        System.out.println("used time="+(end-begin));
    }
}
